package my.example.samplegridview;

import java.text.DecimalFormat;
import java.util.Vector;

import my.example.samplegridview.modal.product;
import o2s.utils.imageHelper;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.res.AssetManager;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class cart extends Activity {

	private cart currentact;
	AssetManager _assetManager;
	ListView cartItemsList;
	LinearLayout footer;
	Context currentContext;
	cartItemAdapter cia;
	Button confirmorder;
	Button cartclearall;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.cart);

		currentcartitems.sortingCurrentCartItem();
		
		currentact = this;
		_assetManager = getAssets();
		Vector<product> products = currentcartitems.cartitems;
		currentContext = this.getBaseContext();

		cartItemsList = (ListView) findViewById(R.id.cartitemlist);
		
		LayoutInflater li = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		footer = (LinearLayout) li.inflate(R.layout.totalprice, null);
		TextView tv = (TextView)footer.findViewById(R.id.totalpriceprice);
		tv.setText("RM " + String.valueOf(currentcartitems.totalCartPrice()));
		cartItemsList.addFooterView(footer);
		
		cia = new cartItemAdapter(this, products);
		cartItemsList.setAdapter(cia);
		
		Button cartback = (Button) findViewById(R.id.cartback);
		cartback.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				finish();
			}
        	
        });
		
		cartclearall = (Button) findViewById(R.id.cartclearall);
		cartclearall.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				currentcartitems.clearCart();
				cia.notifyDataSetChanged();
				reloadListView();
			}
        	
        });

		confirmorder = (Button) findViewById(R.id.cartconfirmorder);
		confirmorder.setOnClickListener(new OnClickListener(){
			@Override
			public void onClick(View v) {
				if(currentcartitems.totalCartPrice() > 0){
					String alertMsg = "Thank you for the orders, we will now prepare your food :)";
					AlertDialog.Builder builder = new AlertDialog.Builder(cart.this);
					builder.setTitle("Thank You!")
							.setMessage(alertMsg)
					       .setCancelable(false)
					       .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
					           @Override
							public void onClick(DialogInterface dialog, int id) {
					        	   currentcartitems.turnAllProductStatus("Placed");
					        	   cia.notifyDataSetChanged();
									reloadListView();
									cartclearall.setVisibility(View.GONE);
					              dialog.cancel();  
					           }
					       });
					AlertDialog alert = builder.create();
					alert.show();
				}
			}
		});
	}

	public class cartItemAdapter extends BaseAdapter {

		private Context mContext;
		private Vector<product> products;

		public cartItemAdapter(Context mContext, Vector<product> products) {
			this.mContext = mContext;
			this.products = products;
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return products.size();
		}

		@Override
		public Object getItem(int position) {
			// TODO Auto-generated method stub
			return products.get(position);
		}

		@Override
		public long getItemId(int position) {
			// TODO Auto-generated method stub
			return 0;
		}

		@Override
		public View getView(final int position, View convertView, ViewGroup parent) {
			final product p = products.get(position);

			LinearLayout productView = null;
			if (convertView == null) { // if it's not recycled, initialize some
										// attributes
				LayoutInflater li = (LayoutInflater) mContext
						.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				productView = (LinearLayout) li
						.inflate(R.layout.cartitem, null);
			} else {
				productView = (LinearLayout) convertView;
			}
			
			// Set image
			ImageView iv = (ImageView)productView.findViewById(R.id.cartitemimage);
			if(p.getImage().length() > 0){
				int indexer = p.getImage().lastIndexOf("/");
				String imageName = p.getImage().substring(indexer+1);
				Bitmap bitmap = imageHelper.readImageFromUrl(imageName, currentContext);
				//Bitmap bitmap = imageHelper.getImageFromResource(_context,p.getImage());
				iv.setImageBitmap(bitmap);
				iv.setScaleType(ImageView.ScaleType.FIT_XY);
			}

			// Set order quantity
			TextView tv = (TextView) productView
					.findViewById(R.id.cartitemorderquantity);
			tv.setText(p.getOrderedQuantity());
			
			// Set price per unit
			tv = (TextView) productView
					.findViewById(R.id.cartitemprice);
			tv.setText(p.getPrice());
			
			// Set remark
			tv = (TextView) productView
				.findViewById(R.id.cartitemremarks);
			tv.setText(p.getRemarks());
			
			// Set ordered by
			tv = (TextView) productView
			.findViewById(R.id.cartitemorderby);
			tv.setText(p.getOrderBy());
			
			// Set Extra Charge
			double extracharge = 0;
			String extraname = "";
			DecimalFormat twoDForm = new DecimalFormat("#.##");
			double orderedQuantity = Double.parseDouble(p.getOrderedQuantity());
			for(int i1=0;i1<p.getProduct_options(true).size();i1++){
				int selectoption = p.getProduct_options(true).get(i1).getSelectedoption();
				extracharge += orderedQuantity * Double.valueOf(p.getProduct_options(true).get(i1).getProduct_option_values(true).get(selectoption).getPrice());
				extraname += p.getProduct_options(true).get(i1).getProduct_option_values(true).get(selectoption).getProoptionvaluedescription().getName() + " ";
			}
			tv = (TextView) productView
				.findViewById(R.id.cartonitemextraitemcharge);
			tv.setText(String.valueOf(extracharge));
			
			// Set price
			tv = (TextView) productView
					.findViewById(R.id.cartonitemsubtotalprice);
			double pricePerUnit = Double.parseDouble(p.getPrice());
			double price = Double.valueOf(twoDForm.format((orderedQuantity*pricePerUnit))) + extracharge;
			tv.setText("RM " +String.valueOf(price));
			
			// Button plus click event
			ImageView buttonplus = (ImageView)productView.findViewById(R.id.cartitemquantityplus);
			buttonplus.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					product p = currentcartitems.cartitems.get(position);
					String orderedQ = p.getOrderedQuantity();
					int orderedQint = Integer.parseInt(orderedQ);
					orderedQint++;
					p.setOrderedQuantity(String.valueOf(orderedQint));
					cia.notifyDataSetChanged();
					reloadListView();
					//setSelection(position);
				}
				
			});
			
			// Button minus click event
			ImageView buttonminus = (ImageView)productView.findViewById(R.id.cartitemquantityminus);
			buttonminus.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					// TODO Auto-generated method stub
					product p = currentcartitems.cartitems.get(position);
					String orderedQ = p.getOrderedQuantity();
					int orderedQint = Integer.parseInt(orderedQ);
					orderedQint--;
					if(orderedQint < 1){
						Toast.makeText(currentContext, "Quantity cannot be less than 1.",Toast.LENGTH_SHORT).show();
					}
					else{
						p.setOrderedQuantity(String.valueOf(orderedQint));
						cia.notifyDataSetChanged();
						reloadListView();
						//setSelection(position);
					}
				}
				
			});
			
			// Item edit event
			productView.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View arg0) {
					Intent i = new Intent(mContext,productdescription.class);
					i.putExtra("id", p.getProduct_id());
					i.putExtra("orderedQuantity",p.getOrderedQuantity());
					i.putExtra("orderRemarks", p.getRemarks());
					i.putExtra("type", "edit");
					i.putExtra("editelementid", position);
					
					int[] options = new int[p.getProduct_options(true).size()];
					for(int i1=0;i1<p.getProduct_options(true).size();i1++){
						options[i1] = p.getProduct_options(true).get(i1).getSelectedoption();
					}
					i.putExtra("orderOptions", options);
					
					currentact.startActivityForResult(i,productdescription.activitycode);
				}
				
			});
			
			// Set name
			tv = (TextView) productView
					.findViewById(R.id.cartitemname);
			if(extraname.length() > 0){
				extraname = " ( " + extraname + " ) " ;
			}
			tv.setText(p.getProdescription().getName() + extraname);
			
			// Set status
			if(p.getProductStatus()!=null){
				tv = (TextView) productView
						.findViewById(R.id.cartitemstatus);
				tv.setText(p.getProductStatus());
			}
			
			//Remove Item
			Button removeButton = (Button) productView.findViewById(R.id.cartonitemremove);
			removeButton.setOnClickListener(new OnClickListener(){

				@Override
				public void onClick(View v) {
					currentcartitems.removeCartItem(position);
					cia.notifyDataSetChanged();
					reloadListView();
				}
				
			});
			
			//If the product is ordered... We will not allow user to remove it;
			if(p.getProductStatus() != null && p.getProductStatus().compareTo("Placed") == 0){
				productView.setOnClickListener(null);
				buttonplus.setVisibility(View.GONE);
				buttonminus.setVisibility(View.GONE);
				removeButton.setVisibility(View.GONE);
				iv = (ImageView)productView.findViewById(R.id.cartonitemplacedimage);
				iv.setVisibility(View.VISIBLE);
			}
			else
			{
				buttonplus.setVisibility(View.VISIBLE);
				buttonminus.setVisibility(View.VISIBLE);
				removeButton.setVisibility(View.VISIBLE);
				iv = (ImageView)productView.findViewById(R.id.cartonitemplacedimage);
				iv.setVisibility(View.GONE);
			}
			
			if(currentcartitems.cartContainedUnOrderedItem()){
				cartclearall.setVisibility(View.VISIBLE);
				confirmorder.setVisibility(View.VISIBLE);
			}
			else{
				cartclearall.setVisibility(View.GONE);
				confirmorder.setVisibility(View.GONE);
			}

			return productView;
		}

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {     
		  super.onActivityResult(requestCode, resultCode, data); 
		  
		  if(requestCode == productdescription.activitycode){
			  cia.notifyDataSetChanged();
			  reloadListView();
		  }
	}
	
	public void reloadListView(){
		cartItemsList.removeFooterView(footer);
		
		TextView tv = (TextView)footer.findViewById(R.id.totalpriceprice);
		tv.setText(String.valueOf(currentcartitems.totalCartPrice()));
		cartItemsList.addFooterView(footer);
	}
	
	public void setSelection(int selectedRow){
		cartItemsList.setSelection(selectedRow);
	}

	/*public class expandableCartItemAdapter extends SimpleExpandableListAdapter{

		public expandableCartItemAdapter(Context context,
				List<? extends Map<String, ?>> groupData,
				int expandedGroupLayout, int collapsedGroupLayout,
				String[] groupFrom, int[] groupTo,
				List<? extends List<? extends Map<String, ?>>> childData,
				int childLayout, int lastChildLayout, String[] childFrom,
				int[] childTo) {
			super(context, groupData, expandedGroupLayout, collapsedGroupLayout, groupFrom,
					groupTo, childData, childLayout, lastChildLayout, childFrom, childTo);
			// TODO Auto-generated constructor stub
		}
		
	}*/
}
